package com.wondersgroup.wssuap.sso.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.wondersgroup.wssuap.sso.credential.Credential;


public class SsoLoginFilter implements Filter {

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {

	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
	 *      javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		Object sessionObject =
			httpRequest.getSession().getAttribute(SsoClientConfig.getInsatance().getLoginedSessionAttribute());
		if (sessionObject != null) {
			chain.doFilter(request, response);
		}
		else {
			
			String ticket = request.getParameter(SsoClientConfig.getInsatance().getTicketParam());
			
			System.out.println("====================="+ticket);
			if (ticket != null) {
				try {
					Credential credential = SsoClientUtils.validate(ticket);
					SsoClientConfig.getInsatance().getSsoJoinedCallback().callback(credential, httpRequest);
					chain.doFilter(request, response);
					return;
				}
				catch (SsoClientException e) {
					e.printStackTrace();
					response.setContentType("text/html;charset=utf-8");
					PrintWriter writer = response.getWriter();
					writer.println("<html>");
					writer.println("<body>");
					writer.println("登录失败:"+e.getMessage());
					writer.println("</body>");
					writer.println("</html>");
				}
			}
			else {
				String loginUrl = String.format("%s?service=%s&params=%s",
						SsoClientConfig.getInsatance().getSsoLoginUrl(),
						URLEncoder.encode(httpRequest.getRequestURL()
								.toString(), "utf-8"), URLEncoder.encode(
								httpRequest.getQueryString(), "utf-8"));

				System.out.println("------------------------------"+loginUrl);
				PrintWriter writer = response.getWriter();
				writer.println("<html>");
				writer.println("<header>");
				writer.println("<script type='text/javascript'>");
				writer.println("document.location='" + loginUrl + "'");
				writer.println("</script>");
				writer.println("</header>");
				writer.println("</html>");
			}
		}
	}

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig config) throws ServletException {
		
		String configFile = config.getInitParameter("config");
		if (configFile == null) {
			throw new ServletException("Filter init parameter 'config' should not be empty");
		}
		Properties properties = new Properties();
		try {
			
		
			properties.load(SsoLoginFilter.class.getResourceAsStream(configFile));
			Set<Entry<Object,Object>> entrySet=properties.entrySet();
			Iterator<Entry<Object,Object>> iter=entrySet.iterator();
			
			while(iter.hasNext())
			{
				Entry<Object,Object> entry=iter.next();
				System.out.println(entry.getKey()+": "+entry.getValue());
			}
			
			
			
			
			
		}
		catch (IOException e) {
			throw new ServletException(String.format("Exception occur when loading config file '%s'", configFile), e);
		}

		SsoClientConfig.init(properties);
	}
}
